package com.ling.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ling.bean.*;
import com.ling.service.*;
import com.ling.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class AnswerController {
    private final AnswerService answerService;
    private final UserUpvoteAnswerService userUpvoteAnswerService;
    private final UserDownvoteAnswerService userDownvoteAnswerService;
    private final AnswerCommentService answerCommentService;
    private final ReportService reportService;
    private final UserService userService;
    private final QuestionService questionService;
    private final UserMessageService userMessageService;
    private final UserAreaService userAreaService;
    @Autowired
    public AnswerController(AnswerService answerService, UserUpvoteAnswerService userUpvoteAnswerService, UserDownvoteAnswerService userDownvoteAnswerService, AnswerCommentService answerCommentService, ReportService reportService, UserService userService, QuestionService questionService, UserMessageService userMessageService, UserAreaService userAreaService) {
        this.answerService = answerService;
        this.userUpvoteAnswerService = userUpvoteAnswerService;
        this.userDownvoteAnswerService = userDownvoteAnswerService;
        this.answerCommentService = answerCommentService;
        this.reportService = reportService;
        this.userService = userService;
        this.questionService = questionService;
        this.userMessageService = userMessageService;
        this.userAreaService = userAreaService;
    }

    //返回指定问题的回答，分页
    @RequestMapping(value = "/question/{questionId}/answers/{pn}", method = RequestMethod.GET)
    @ResponseBody
    public Msg getAnswerList(@PathVariable String questionId, @PathVariable Integer pn) {
        PageHelper.startPage(pn, 10);
        List<Answer> answerListByQuestionId = answerService.getAnswerListByQuestionId(questionId);
        PageInfo<Answer> pageInfo = new PageInfo<>(answerListByQuestionId);
        return Msg.success().add("pageInfo", pageInfo);
    }

    //提交回答
    @RequestMapping(value = "/submitAnswer", method = RequestMethod.POST)
    @ResponseBody
    public Msg submitAnswer(@RequestParam String answerContent, @RequestParam String questionId, @RequestParam String userId, HttpSession httpSession) {
        Answer answer = new Answer();
        answer.setAnswercontent(answerContent);
        answer.setDownvotenum(0);
        answer.setEdittime(new Date());
        String answerId = StringUtil.getRandomString(16);
        answer.setId(answerId);
        answer.setQuestionid(questionId);
        answer.setTop(false);
        answer.setUpvotenum(0);
        answer.setUserid(userId);
        answerService.saveAnswer(answer);

        Question question_db = questionService.getUserQuestionById(questionId);
        UserMessage userMessage = new UserMessage();
        userMessage.setEdittime(new Date());
        userMessage.setFromuserid(userId);
        User userById = userService.getUserById(userId);
        String nickname = userById.getNickname();
        userMessage.setFromusername(nickname);
        userMessage.setHasread(0);
        userMessage.setId(StringUtil.getRandomString(16));
        userMessage.setMessagecontent("回答了你发布的问题@ " + question_db.getQuestiontitle()+" 。");
        userMessage.setMessagetype(3);
        userMessage.setMessagetypeid(questionId);
        //谁发布的问题
        userMessage.setUserid(question_db.getUserid());
        userMessageService.saveUserMessage(userMessage);

        //经验值+5
        userById.setJiyan(userById.getJiyan()+5);
        userService.updateUserProfile(userById);
        httpSession.setAttribute("user",userById);
        //能力+5
        UserArea userArea = userAreaService.getUserArea(userId, question_db.getAreaid());
        if (userArea != null) {
            userArea.setAbility(userArea.getAbility() + 5);
            userAreaService.updateAbility(userArea);
        }else{
            UserArea userArea1 = new UserArea();
            userArea1.setId(StringUtil.getRandomString(16));
            userArea1.setAbility(0);
            userArea1.setAreaid(question_db.getAreaid());
            userArea1.setUserid(userId);
            userAreaService.saveUserArea(userArea1);
        }
        return Msg.success().add("answerId", answerId);
    }

    //赞同回答
    @PostMapping("/upvoteAnswer")
    @ResponseBody
    public Msg upvoteAnswer(@RequestParam String answerId, HttpSession session) {
        //判断登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请先登录！");
        }
        //判断是否存在该记录
        if (userUpvoteAnswerService.existUserUpvoteAnswer(user.getId(), answerId)) {
            return Msg.fail().add("error", "您已赞同该回答，请不要重复操作！");
        }
        UserUpvoteAnswer userUpvoteAnswer = new UserUpvoteAnswer();
        userUpvoteAnswer.setId(StringUtil.getRandomString(16));
        userUpvoteAnswer.setUpvoteanswerid(answerId);
        userUpvoteAnswer.setUserid(user.getId());
        //插入数据库
        userUpvoteAnswerService.addUserUpvoteAnswer(userUpvoteAnswer);
        Answer answerById = answerService.getAnswerById(answerId);
        answerById.setUpvotenum(answerById.getUpvotenum() + 1);
        answerService.updateAnswer(answerById);
        Question question = questionService.getUserQuestionById(answerById.getQuestionid());
        //用户收到消息
        UserMessage userMessage = new UserMessage();
        userMessage.setEdittime(new Date());
        userMessage.setFromuserid(user.getId());
        userMessage.setFromusername(user.getNickname());
        userMessage.setHasread(0);
        userMessage.setId(StringUtil.getRandomString(16));
        userMessage.setMessagecontent("赞同了你编辑的回答 @ "+question.getQuestiontitle()+"。");
        userMessage.setMessagetype(4);
        userMessage.setMessagetypeid(answerId);
        //谁编辑的回答
        userMessage.setUserid(answerById.getUserid());
        userMessageService.saveUserMessage(userMessage);
        return Msg.success();
    }

    //反对回答
    @PostMapping("/downvoteAnswer")
    @ResponseBody
    public Msg downvoteAnswer(@RequestParam String answerId, HttpSession session) {
        //判断登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请先登录！");
        }
        //查看是否存在记录
        if (userDownvoteAnswerService.existUserDownvoteAnswer(user.getId(), answerId)) {
            return Msg.fail().add("error", "您已反对该回答，请不要重复操作！");
        }
        UserDownvoteAnswer userDownvoteAnswer = new UserDownvoteAnswer();
        userDownvoteAnswer.setId(StringUtil.getRandomString(16));
        userDownvoteAnswer.setUserid(user.getId());
        userDownvoteAnswer.setDownvoteanswerid(answerId);

        //插入数据库
        userDownvoteAnswerService.addUserDownvoteAnswer(userDownvoteAnswer);
        Answer answerById = answerService.getAnswerById(answerId);
        answerById.setDownvotenum(answerById.getDownvotenum() + 1);
        answerService.updateAnswer(answerById);
        Question question = questionService.getUserQuestionById(answerById.getQuestionid());
        //用户收到消息
        UserMessage userMessage = new UserMessage();
        userMessage.setEdittime(new Date());
        userMessage.setFromuserid(user.getId());
        userMessage.setFromusername(user.getNickname());
        userMessage.setHasread(0);
        userMessage.setId(StringUtil.getRandomString(16));
        userMessage.setMessagecontent("反对了你编辑的回答 @ "+question.getQuestiontitle()+"。");
        userMessage.setMessagetype(4);
        userMessage.setMessagetypeid(answerId);
        //谁编辑的回答
        userMessage.setUserid(answerById.getUserid());
        userMessageService.saveUserMessage(userMessage);
        return Msg.success();
    }

    //根据分页获取指定回答的评论信息
    @GetMapping(value = "/answer/{answerId}/comments/{pn}")
    @ResponseBody
    public Msg getComment(@PathVariable String answerId, @PathVariable Integer pn) {
        //开始分页
        PageHelper.startPage(pn, 10);
        List<AnswerComment> answerCommentByAnswerId = answerCommentService.getAnswerCommentByAnswerId(answerId);
        PageInfo<AnswerComment> pageInfo = new PageInfo<>(answerCommentByAnswerId);
        return Msg.success().add("pageInfo", pageInfo);
    }

    //用户举报回答
    @GetMapping(value = "/report/answer/{answerId}")
    @ResponseBody
    public Msg reportAnswer(@PathVariable String answerId, HttpSession session) {
        //判断用户登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请先登录！");
        }
        Report report = new Report();
        report.setHasread(0);
        report.setId(StringUtil.getRandomString(16));
        report.setReportfieldid(answerId);
        report.setReporttype(3);
        report.setUserid(user.getId());
        if (reportService.existReport(report)) {
            return Msg.fail().add("error", "您已举报该回答，请不要重复操作！");
        }
        //保存数据库
        reportService.saveReport(report);
        Answer answerById = answerService.getAnswerById(answerId);
        Question question = questionService.getUserQuestionById(answerById.getQuestionid());

        //用户收到消息
        UserMessage userMessage = new UserMessage();
        userMessage.setEdittime(new Date());
        userMessage.setFromuserid(user.getId());
        userMessage.setFromusername(user.getNickname());
        userMessage.setHasread(0);
        userMessage.setId(StringUtil.getRandomString(16));
        userMessage.setMessagecontent("举报了你编辑的回答 @ "+question.getQuestiontitle()+"。");
        userMessage.setMessagetype(4);
        userMessage.setMessagetypeid(answerId);
        //谁编辑的回答
        userMessage.setUserid(answerById.getUserid());
        userMessageService.saveUserMessage(userMessage);
        return Msg.success();
    }

    //回答置顶
    @GetMapping(value = "/setTop/answer/{answerId}")
    @ResponseBody
    public Msg setTopAnswer(@PathVariable String answerId, HttpSession session) {
        //判断用户登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请先登录！");
        }
        Answer answer = new Answer();
        answer.setId(answerId);
        answer.setTop(true);
        //修改数据库
        answerService.updateAnswer(answer);
        return Msg.success();
    }

    //回答取消置顶
    @GetMapping(value = "/cancelSetTop/answer/{answerId}")
    @ResponseBody
    public Msg cancelSetTopAnswer(@PathVariable String answerId, HttpSession session) {
        //判断用户登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请先登录！");
        }
        Answer answer = new Answer();
        answer.setId(answerId);
        answer.setTop(false);
        //修改数据库
        answerService.updateAnswer(answer);
        return Msg.success();
    }

    @GetMapping(value = "/delete/answer/{answerId}")
    @ResponseBody
    public Msg deleteAnswer(@PathVariable String answerId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请先登录！");
        }
        answerService.deleteAnswer(answerId);
        return Msg.success();
    }

    //管理员删除回答
    @PostMapping("/delAnswer/{answerId}")
    @ResponseBody
    public Msg delAnswer(@PathVariable String answerId) {
        answerService.deleteAnswer(answerId);
        return Msg.success();
    }

    //跳转到查看我的回答
    @GetMapping(value = "/answer-mine")
    public String goToAnswerMine() {
        return "answer-mine";
    }

    //获取所有我的回答,分页
    @GetMapping(value = "/answer/mine/{pn}")
    @ResponseBody
    public Msg getAllMyAnswer(HttpSession session, @PathVariable Integer pn) {
        //登录判断
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请先登录！");
        }
        //用户已登录，开始分页
        PageHelper.startPage(pn, 10);
        List<Answer> allUserAnswer = answerService.getAllUserAnswer(user.getId());
        PageInfo<Answer> pageInfo = new PageInfo<>(allUserAnswer);
        return Msg.success().add("pageInfo", pageInfo);
    }

    //提交回答修改
    @PostMapping("/updateAnswer/{answerId}")
    @ResponseBody
    public Msg updateAnswer(HttpSession session,@PathVariable String answerId,@RequestParam String updateContent) {
        //判断用户登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请先登录！");
        }
        //判断用户权限
        Answer answer = answerService.getAnswerById(answerId);
        if (!answer.getUserid().equals(user.getId())) {
            return Msg.fail().add("error", "你无权修改该回答！");
        }
        //提交修改
        answer.setAnswercontent(answer.getAnswercontent()+updateContent);
        answer.setEdittime(new Date());
        answerService.updateAnswer(answer);
        return Msg.success();
    }

}
